package cd.safe.school.activity;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cd.safe.school.R;
import cd.safe.school.adapter.GalleryAdapter;
import cd.safe.school.adapter.GridItemAdapter;
import cd.safe.school.adapter.MusicAdapter;
import cd.safe.school.bean.FileItem;
import cd.safe.school.util.NetTool;
import cd.safe.school.util.Parse;
import cd.safe.school.util.XmlUtil;
import cd.safe.school.util.ZipUtil;

public class EnglishEditDetailActivity extends Activity implements
		OnClickListener {

	private List<Bitmap> lists = new ArrayList<Bitmap>();
	private LinearLayout add_img;
	private LinearLayout add_music;
	private LinearLayout add_text;
	private static List<String> imgpaths = new ArrayList<String>();
	private LayoutInflater in;
	private static TextView xs_text;
	private Handler handler = new Handler();
	private GridView gd;
	private GridItemAdapter ad;
	private static String music_name;
	private static String music_path;
	private TextView xs_music_name;
	private String text;

	private static String uploadurl = "http://125.64.132.84:8080/jxt/app/res/upload";
	private static List<String> imgnames;
	private String textcontent;
	public String musicname;
	private static String path;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.englishdictation_02);
		String tag = getIntent().getStringExtra("tag");
		path = getIntent().getStringExtra("path");
		if ("composition".equals(tag)) {
			HomeActivity.rutn = 8;

		} else if ("synparse".equals(tag)) {
			HomeActivity.rutn = 9;
		} else if ("error".equals(tag)) {
			HomeActivity.rutn = 10;
		} else {
			HomeActivity.rutn = 4;
		}

		xs_music_name = (TextView) findViewById(R.id.xs_music_name);
		add_img = (LinearLayout) findViewById(R.id.add_img);
		add_music = (LinearLayout) findViewById(R.id.add_music);
		add_text = (LinearLayout) findViewById(R.id.add_text);
		xs_text = (TextView) findViewById(R.id.xs_text);
		gd = (GridView) findViewById(R.id.xs_img);
		add_img.setOnClickListener(this);
		add_music.setOnClickListener(this);
		add_text.setOnClickListener(this);
		in = this.getLayoutInflater();
		musicname = XmlUtil.musicname;
		textcontent = XmlUtil.readfile(path + "/tt.text");
		imgnames = XmlUtil.imgnames;

		if (textcontent != null) {
			xs_text.setText(textcontent);
		}
		if (musicname != null) {
			xs_music_name.setText(musicname.substring(0,
					musicname.lastIndexOf(".")));
			music_path = path + "/" + musicname;

		}

		if (imgnames.size() > 0) {
			imgpaths.clear();
			for (int i = 0; i < imgnames.size(); i++) {
				String path2 = path + "/" + imgnames.get(i);
				imgpaths.add(path2);
				// BitmapFactory.Options options = new BitmapFactory.Options();
				// options.inJustDecodeBounds = true;
				// Bitmap bt = BitmapFactory.decodeFile(path, options);
				// float realWidth = options.outWidth;
				// float realHeight = options.outHeight;
				// int scale = (int) ((realHeight > realWidth ? realHeight
				// : realWidth) / 100);
				// if (scale <= 0) {
				// scale = 1;
				// }
				// options.inSampleSize = scale;
				// options.inJustDecodeBounds = false;
				// bt = BitmapFactory.decodeFile(path, options);

			}

		}

		ad = new GridItemAdapter(imgpaths, this);

		gd.setAdapter(ad);

		// adapter = new GalleryAdapter(this, lists);
		// 设置图片之间的距离
		// gly.setSpacing(5);
		// gly.setAdapter(adapter);
		//
		// gly.setOnItemLongClickListener(new OnItemLongClickListener() {
		//
		// @Override
		// public boolean onItemLongClick(AdapterView<?> parent, View view,
		// int position, long id) {
		// for (int i = 0; i < lists.size(); i++) {
		// if (i != position) {
		// RelativeLayout rl = (RelativeLayout) gly.getChildAt(i);
		// ImageView gImageView = (ImageView) rl
		// .findViewById(R.id.gallery_qac);
		// gImageView.setVisibility(View.GONE);
		// }
		//
		// }
		//
		// ImageView gallery_qac = (ImageView) view
		// .findViewById(R.id.gallery_qac);
		// gallery_qac.setVisibility(View.VISIBLE);
		//
		// return false;
		// }
		// });
		//
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.add_img:
			Intent i = new Intent(
					Intent.ACTION_PICK,
					android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
			startActivityForResult(i, 1);

			break;
		case R.id.add_music:
			Intent intent = new Intent(EnglishEditDetailActivity.this,
					SelectMusicActivity.class);
			startActivityForResult(intent, 101);

			break;
		case R.id.add_text:
			final View vw = in.inflate(R.layout.dialogview, null);
			final EditText ed = (EditText) vw.findViewById(R.id.dialogview);
			ed.setText(xs_text.getText().toString());

			new AlertDialog.Builder(EnglishEditDetailActivity.this)
					.setTitle("请输入")
					.setView(vw)
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {

									// Toast.makeText(
									// EnglishEditDetailActivity.this,
									// ed.getText().toString(),
									// Toast.LENGTH_SHORT).show();
									handler.post(new Runnable() {

										@Override
										public void run() {
											xs_text.setText(ed.getText()
													.toString());
											text = ed.getText().toString();

										}
									});

								}
							}).setNegativeButton("取消", null).show();

			break;

		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 1 && resultCode == RESULT_OK && null != data) {

			Uri selectedImage = data.getData();

			String[] filePathColumn = { MediaStore.Images.Media.DATA };
			Cursor cursor = getContentResolver().query(selectedImage,

			filePathColumn, null, null, null);

			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);

			String picturePath = cursor.getString(columnIndex);

			String imgname = picturePath
					.substring(picturePath.lastIndexOf("/") + 1);
			imgnames.add(imgname);
			imgpaths.add(picturePath);
			if (imgpaths.size() > 4) {
				gd.setLayoutParams(new LinearLayout.LayoutParams(
						LayoutParams.FILL_PARENT, 220));

			}

			ad.notifyDataSetChanged();
			cursor.close();

		}
		if (requestCode == 101 && resultCode == RESULT_OK && null != data) {
			music_name = data.getStringExtra("name");
			music_path = data.getStringExtra("path");
			handler.post(new Runnable() {

				@Override
				public void run() {
					xs_music_name.setText(music_name);

				}
			});

		}

	}

	public static void upload() {

		try {
			List<File> files = new ArrayList<File>();

			XmlUtil.writexml(path + "/GZ.xml",
					music_path.substring(music_path.lastIndexOf("/") + 1),
					xs_text.getText().toString(), imgnames);
			XmlUtil.writefile(path + "/tt.text", xs_text.getText().toString());
			File zipfile = new File(path + "/kejian.zip");
			for (String path : imgpaths) {
				File f = new File(path);
				files.add(f);
			}
			File filexml = new File(path + "/GZ.xml");
			File mus = new File(music_path);
			File textfile = new File(path + "/tt.text");
			files.add(mus);
			files.add(textfile);
			files.add(filexml);

			ZipUtil.zipFiles(files, zipfile, "");

			final Map<String, Object> params = new HashMap<String, Object>();
			params.put("filename", "GZ.zip");
			params.put("msg", "1");
			params.put("infoType", "1");
			params.put("receiveId", "2");
			params.put("filetype", "1");

			final List<FileItem> items = new ArrayList<FileItem>();
			FileItem fi = new FileItem();
			fi.setFieldName("file");
			fi.setPath(zipfile.getAbsolutePath());
			items.add(fi);
			new Thread(new Runnable() {

				@Override
				public void run() {
					String ret = NetTool.postFileFormParams(uploadurl, params,
							items);

				}
			}).start();

		} catch (IOException e) {
			System.out.println("上传失败");
			e.printStackTrace();
		}

	}

	@Override
	public void finish() {

		imgpaths.clear();
		imgnames.clear();
		super.finish();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			imgnames.clear();
		}
		return false;
	}

}
